﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Generic;
using EzDesk.Utility.Json;
using EzDesk.Utility.TimerService;
using EzDesk.Apps.Interface.Attendance;

namespace EzDesk.Apps.ServiceImpl.Attendance
{
    // 定义为内部类，方便访问AttendanceService私有变量

    public partial class AttendanceService : ContainerAccessorBase, IAttendanceService
    {
        /// <summary>
        /// 每日最早的上班时间时，发送考勤统计信息给人事的Feed
        /// </summary>
        class DailyAttendanceStaticsTask : EverydayTimerTask
        {
            private readonly AttendanceService _attendanceService;

            public DailyAttendanceStaticsTask(TimeSpan dayExecuteTime, AttendanceService attendanceService)
                : base("DailyAttendanceStaticsTask", dayExecuteTime)
            {
                _attendanceService = attendanceService;
            }

            protected sealed override void doExecute()
            {
                // todo: 如果头一天没什么特别的事情就不用发Feed了

                DateTime attendanceDay = NextDay.AddDays(-1);
                string dateStr = attendanceDay.ToFullDate();
                string dateEpoch = attendanceDay.ToEpoch().ToString();

                var allUserList = _attendanceService._ezApiClient.GetSimpleUserInfos("everyone");

                var dayAttendanceDetailList = allUserList
                    .Select(user => _attendanceService.GetDayAttendanceEvaluation(user.Id, attendanceDay).Result);


                var absenseCount = dayAttendanceDetailList.Count(p => p.IsAbsense);
                var extraWorkCount = dayAttendanceDetailList.Count(p => p.IsExtraWork);

                var evaluationBuilder = new StringBuilder("  ");

                evaluationBuilder.AppendFormat("加班 {0} 人 ", extraWorkCount);
                evaluationBuilder.AppendFormat("旷工 {0} 人 ", absenseCount);

                var feedData = new Dictionary<string, string> {
                    {"dateStr", dateStr}, 
                    {"dateEpoch", dateEpoch},
                    {"evaluationStr", evaluationBuilder.ToString()}
                };

                // 发送目标：所有人事
                string targetMemberString = _attendanceService._ezApiClient
                    .GetGroupByName("attendance_hr")
                    .MemberString;

                _attendanceService._ezApiClient.SendFeed(
                    FeedTemplateStr_attendance_dailyAttendanceStatics,
                    JsonHelper.ConvertToJson(feedData),
                    targetMemberString
                    );
            }
        }
    }
}
